package T5;

public class Matrix {
    double[][] data;

    public Matrix(double[][] data) throws MIllegalArgumentException {
        if (data == null || data.length == 0 || data[0].length == 0) {
            throw new MIllegalArgumentException("矩阵行数或列数非法");
        }
        this.data = data;
    }

    public Matrix(int rows, int cols) throws MIllegalArgumentException {
        if (rows <= 0 || cols <= 0) {
            throw new MIllegalArgumentException("矩阵行数或列数非法");
        }
        data = new double[rows][cols];
    }

    public double getData(int row, int col) {
        if (!isValidIndex(row, col)) {
            throw new IllegalIndexException("矩阵行号或列号非法");
        }
        return data[row][col];
    }

    // 设置矩阵中指定位置的元素值
    public void setData(int row, int col, double value) {
        if (!isValidIndex(row, col)) {
            throw new IllegalIndexException("矩阵行号或列号非法");
        }
        data[row][col] = value;
    }

    // 获取矩阵的行数
    public int getRows() {
        return data.length;
    }

    // 获取矩阵的列数
    public int getCols() {
        return data[0].length;
    }

    public Matrix mulitiply(Matrix m) throws MIllegalArgumentException {
        if (this.getCols() != m.getRows()) {
            throw new MatrixMultiplicationException("矩阵无法相乘");
        }
//        计算两个矩阵的乘积
        int rowsA = this.getRows();
        int colsA = this.getCols();
        int colsB = m.getCols();

        Matrix result = new Matrix(rowsA,colsB);//创建对象
        for (int i = 0; i < rowsA; i++) { // 遍历结果矩阵的每一行
            for (int j = 0; j < colsB; j++) { // 遍历结果矩阵的每一列
                double sum = 0; // 初始化sum用于存储累加结果
                for (int k = 0; k < colsA; k++) { // 遍历当前矩阵A的列和矩阵B的行
                    // 乘积并累加：this.getData(i, k) 是矩阵A的第i行第k列元素，m.getData(k, j) 是矩阵B的第k行第j列元素
                    sum += this.getData(i, k) * m.getData(k, j);
                }
                // 将累加的乘积结果存储在结果矩阵的第i行第j列
                result.setData(i, j, sum);
            }
        }
        return result;
    }

    private boolean isValidIndex(int row, int col) {
//        检查索引是否有效
        return row >= 0 && row < getRows() && col >= 0 && col < getCols();
    }

    public void print (){
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[0].length; j++) {
                System.out.print(data[i][j]+" ");
            }
            System.out.println();
        }
    }
}
